#!/usr/bin/env python3
"""
测试修复后的subprocess版本
"""

import asyncio
from pathlib import Path
from app.services.video_splitter import VideoSplitter
import shutil

async def test_fixed_subprocess():
    """测试修复后的subprocess版本"""
    
    video_path = Path("uploads/ed0df223-f7c5-4a97-9ace-f3bed83ca3a3.mp4")
    
    if not video_path.exists():
        print(f"❌ 视频文件不存在: {video_path}")
        return
    
    print(f"🧪 测试修复后的subprocess版本")
    print(f"📹 视频文件: {video_path}")
    
    # 清理之前的片段
    video_id = video_path.stem
    segment_dir = Path("uploads/segments") / video_id
    if segment_dir.exists():
        shutil.rmtree(segment_dir)
        print(f"🧹 已清理旧片段目录")
    
    splitter = VideoSplitter()
    
    try:
        # 测试单个片段提取
        print(f"\n1️⃣ 测试单个片段提取...")
        
        segment_dir.mkdir(parents=True, exist_ok=True)
        segment_path = segment_dir / "test_single.mp4"
        
        success = await splitter._extract_segment(
            video_path, segment_path, 0.0, 10.0
        )
        
        print(f"   提取结果: {'✅ 成功' if success else '❌ 失败'}")
        
        if success and segment_path.exists():
            file_size = segment_path.stat().st_size
            print(f"   文件大小: {file_size} bytes")
        
        # 测试完整拆分（5个片段）
        print(f"\n2️⃣ 测试完整拆分（5个片段）...")
        
        # 清理测试文件
        if segment_dir.exists():
            shutil.rmtree(segment_dir)
        
        result = await splitter.split_video_by_duration(
            video_path, 
            segment_duration=60,
            max_segments=5,
            min_segment_duration=10
        )
        
        segments_count = len(result.get('segments', []))
        print(f"   拆分结果: {segments_count} 个片段")
        
        if segments_count > 0:
            print(f"   ✅ 拆分成功！")
            
            # 检查文件
            for i, segment in enumerate(result['segments']):
                segment_path = Path(segment['path'])
                if segment_path.exists():
                    size = segment_path.stat().st_size
                    print(f"     片段{i+1}: {segment['filename']} ({size} bytes)")
                else:
                    print(f"     ❌ 片段{i+1}: {segment['filename']} 文件不存在")
        else:
            print(f"   ❌ 拆分失败")
        
    except Exception as e:
        print(f"❌ 测试失败: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    asyncio.run(test_fixed_subprocess())